//
//  HomeController.m
//  MyNewWeiBo
//
//  Created by wpapple on 16/5/30.
//  Copyright © 2016年 heron. All rights reserved.
//

#import "HomeController.h"
#import "UIBarButtonItem+btn.h"
#import "HomeTitleButton.h"
#import "PopUpView.h"
#import "Account.h"
#import "IWStatus.h"
#import "LoadMoreFootView.h"

@interface HomeController ()

@property (nonatomic, strong) NSMutableArray * statuses;

@property (nonatomic, strong) UIRefreshControl * myRefreshControl;

@end

@implementation HomeController

- (NSMutableArray *)statuses{
    if (!_statuses) {
        _statuses = [NSMutableArray array];
    }
    return _statuses;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    
    [self setupNav];
    
    BOOL isLogin = [Account isLogin];
    if (isLogin) {
        [self loadNewStatuses:nil];
        
        UIRefreshControl * refreshControl = [[ UIRefreshControl alloc]init];
        self.myRefreshControl = refreshControl;
        [refreshControl addTarget:self action:@selector(loadNewStatuses:) forControlEvents:UIControlEventValueChanged];
        [self.tableView addSubview:refreshControl];
        
//        [self.myRefreshControl beginRefreshing];
        
    }
    
}

- (void)setupNav{
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc]itemWithImageName:@"navigationbar_friendsearch" withHightImageName:@"navigationbar_friendsearch_highlighted"];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc]itemWithImageName:@"navigationbar_pop" withHightImageName:@"navigationbar_pop_highlighted"];
    [rightItem btnClickWithTarget:self with:@selector(quickView)];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    HomeTitleButton * titleBtn = [HomeTitleButton buttonWithType:UIButtonTypeCustom];
    [titleBtn setTitle:@"首页" forState:UIControlStateNormal];
    [titleBtn setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
    [titleBtn setImage:[UIImage imageNamed:@"navigationbar_arrow_up"] forState:UIControlStateSelected];
    [titleBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [titleBtn addTarget:self action:@selector(titleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [titleBtn sizeToFit];
    self.navigationItem.titleView = titleBtn;
}

- (void)loadNewStatuses:(UIRefreshControl *)refreshControl{
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    NSMutableDictionary * parameters = [NSMutableDictionary dictionary];
    parameters[@"access_token"] = [Account accountFromSandbox].access_token;
    parameters[@"count"] = @20;
    
    NSString * firsStatusIdstr = [[self.statuses firstObject]idstr];
    
    if (firsStatusIdstr != nil) {
        parameters[@"since_id"] = firsStatusIdstr;
    }
    
    
    NSString * urlStr = @"https://api.weibo.com/2/statuses/home_timeline.json";
    [manager GET:urlStr parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        NSArray * newStatus = responseObject[@"statuses"];
        NSArray * models = [IWStatus objectArrayWithKeyValuesArray:newStatus];
        
//        [self.statuses addObjectsFromArray:models];
        
        NSRange range = NSMakeRange(0, models.count);
        NSIndexSet * indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
        [self.statuses insertObjects:models atIndexes:indexSet];
        
        [self.tableView reloadData];
        
        [self.myRefreshControl endRefreshing];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@",error);
    }];
}

- (void)quickView{
    UIStoryboard * story = [UIStoryboard storyboardWithName:@"Scan" bundle:nil];
    UITabBarController * tabBarC = [story instantiateInitialViewController];
    [self presentViewController:tabBarC animated:YES completion:nil];
}

//弹出小窗口
- (void)titleBtnClick:(UIButton *)sender{
    sender.selected = !sender.selected;
    
    UITableView * tableView = [[UITableView alloc]init];
    tableView.height = 200;
    
    [PopUpView popUpViewWithContentView:tableView clickView:sender withTarget:self display:^{
        sender.selected = !sender.selected;
    }];
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return self.statuses.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString * identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    
    IWStatus * status = self.statuses[indexPath.row];
    IWUser * user = status.user;
    cell.textLabel.text = user.name;
    cell.detailTextLabel.text = status.text;
    
    
    // Configure the cell...
    
    return cell;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat finalY = scrollView.contentSize.height + scrollView.contentInset.bottom - scrollView.height;
    
    if (self.tableView.tableFooterView != nil || self.statuses.count == 0) {
        return;
    }
    
    if (scrollView.contentOffset.y > finalY) {
        self.tableView.tableFooterView = [LoadMoreFootView loadMoreFootView];
        [self loadMoreData];
    }
}

- (void)loadMoreData{
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    
    NSString * urlStr = @"https://api.weibo.com/2/statuses/home_timeline.json";
    NSMutableDictionary * parameters = [NSMutableDictionary dictionary];
    parameters[@"access_token"] = [Account accountFromSandbox].access_token;
    parameters[@"count"] = @20;
    NSString * lastStatusIdstr = [[self.statuses lastObject]idstr];
    
    if (lastStatusIdstr != nil) {
        parameters[@"since_id"] = @([lastStatusIdstr longLongValue] - 1);
    }
    [manager GET:urlStr parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        NSArray * newStatus = responseObject[@"statuses"];
        NSArray * models = [IWStatus objectArrayWithKeyValuesArray:newStatus];
        [self.statuses addObjectsFromArray:models];
        [self.tableView reloadData];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.tableView.tableFooterView = nil;
        });
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@",error);
        self.tableView.tableFooterView = nil;
    }];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
